package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.CategoryBrandMapper;
import com.qingcheng.dao.CategoryMapper;
import com.qingcheng.dao.SkuMapper;
import com.qingcheng.dao.SpuMapper;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.Category;
import com.qingcheng.pojo.goods.CategoryBrand;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.SpuService;
import com.qingcheng.util.CacheKey;
import com.qingcheng.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SpuService.class)
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 审核商品
     * @param id
     * @param status
     * @param message
     */
    public void updateAudit(String id, String status, String message) {
        Spu spu = new Spu();
        spu.setId(id);
        spu.setStatus(status);
        //如果审核通过直接上架,更改上架状态
        if ("1".equals(status)){
            spu.setIsMarketable("1");
        }
        //更新商品的审核
        spuMapper.updateByPrimaryKeySelective(spu);

        //商品审核表写日志信息

    }

    /**
     * 下架商品
     * @param id
     */
    public void updatePull(String id) {
        Spu spu = new Spu();
        spu.setId(id);
        spu.setIsMarketable("0");

        spuMapper.updateByPrimaryKeySelective(spu);

    }

    /**
     * 上架商品
     * @param id
     */
    public void updatePut(String id) {
        //如果未通过审核是不可以上架商品的
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //未通过审核进行上架操作,报出异常
        if (!"1".equals(spu.getStatus())){
            throw new RuntimeException("商品未通过审核,禁止上架");
        }else{
            spu.setIsMarketable("1");
            spuMapper.updateByPrimaryKeySelective(spu);
        }
    }

    /**
     * 批量上架商品
     * @param ids
     */
    public void updatePutMany(String[] ids) {
        for (String id : ids) {
            updatePut(id);
        }
    }

    /**
     * 逻辑删除 is_delete
     * @param id
     */
    public void logicDelete(String id) {

        Spu spu = new Spu();
        spu.setIsDelete("1");
        spu.setId(id);

        spuMapper.updateByPrimaryKeySelective(spu);


    }

    /**
     * 把所有的价格存到redis中
     */
    public void saveAllPriceToRedis() {

        if(!redisTemplate.hasKey(CacheKey.SKU_PRICE)){
            List<Sku> skus = skuMapper.selectAll();
            for (Sku sku : skus) {
                if ("1".equals(sku.getStatus())){
                    redisTemplate.boundHashOps(CacheKey.SKU_PRICE).put(sku.getId(),sku.getPrice());
                }
            }
        }
    }

    /**
     * 根据id查询价格
     * @param id
     * @return
     */
    public Integer findPrice(String id) {
        Integer o = (Integer) redisTemplate.boundHashOps(CacheKey.SKU_PRICE).get(id);
        return o;
    }


    /**
     * 返回全部记录
     * @return
     */
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Spu> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectAll();
        return new PageResult<Spu>(spus.getTotal(),spus.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Spu> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectByExample(example);
        return new PageResult<Spu>(spus.getTotal(),spus.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Spu findById(String id) {
        return spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     * @param spu
     */
    public void add(Spu spu) {
        spuMapper.insert(spu);
    }

    /**
     * 修改
     * @param spu
     */
    public void update(Spu spu) {
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     *  删除
     * @param id
     */
    public void delete(String id) {
        spuMapper.deleteByPrimaryKey(id);
    }

    /**
     * 当客户上架一个商品时需要保存的spu信息和sku信息
     * @param goods
     */

    @Transactional
    public void saveGoods(Goods goods) {

        //向数据库存储spu的相关信息
        Spu spu = goods.getSpu();
        String spuId = spu.getId();
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
        Date date = new Date();



        //如果spu的id值为空说明是新增的数据
        if (spuId==null){
            //新增spu
            spu.setId(idWorker.nextId()+"");
            spu.setSaleNum(0);//销量
            spu.setCommentNum(0);//评论数
            spuMapper.insert(spu);


            //新增sku
            //查看该商品属于哪个类目

            //向数据库存储sku的相关信息
            List<Sku> skuList = goods.getSkuList();
            for (Sku sku : skuList) {

                //防止没有值的时候,转json发生异常
                if(sku.getSpec()==null || "".equals(sku.getSpec())){

                    sku.setSpec("{}");
                }


                sku.setId(idWorker.nextId()+""); //id
                String skuName="";
                Map<String,String> specMap = JSON.parseObject(sku.getSpec(),Map.class);
                for (String s : specMap.values()) {
                    skuName+=" "+s;
                }
                sku.setName(spu.getName()+skuName);     //name
                sku.setSpuId(spu.getId()); //外键
                sku.setCreateTime(date);  //创建日期
                sku.setUpdateTime(date);    //修改日期
                sku.setCategoryId(category.getId());  //  分类id
                sku.setCategoryName(category.getName()); //分类名
                sku.setCommentNum(0);  //评论数
                sku.setSaleNum(0);  //销量
                skuMapper.insert(sku);
            }
        }else {
            //修改spu   修改sku

            //修改spu
            Example example = new Example(Sku.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spuId", spuId);
            spuMapper.deleteByExample(example);  //直接删除所有的sku信息,准备重新存
            spuMapper.updateByPrimaryKeySelective(spu);


            //修改sku(重新存)
            List<Sku> skuList = goods.getSkuList();
            for (Sku sku : skuList) {

                //防止没有值的时候,转json发生异常
                if(sku.getSpec()==null || "".equals(sku.getSpec())){

                    sku.setSpec("{}");
                }


                String skuName = "";
                Map<String, String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
                for (String s : specMap.values()) {
                    skuName += " " + s;
                }
                sku.setName(spu.getName() + skuName);     //name


                sku.setUpdateTime(date);    //修改日期


                skuMapper.insert(sku);


            }


            //维护tb_category_brand商品分类表的关系,先查有无对应的关系,没有再添加对应关系
            CategoryBrand cb = new CategoryBrand();
            cb.setBrandId(spu.getBrandId());
            cb.setCategoryId(spu.getCategory3Id());
            int count = categoryBrandMapper.selectCount(cb);
            if (count == 0) {
                categoryBrandMapper.insert(cb);
            }


        }

    }

    //根据id去查询商品的spu信息
    public Goods findGoodsById(String id) {
        //查商品spu信息
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //查商品sku信息
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", id);
        List<Sku> skus = skuMapper.selectByExample(example);

        //组装Goods对象
        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skus);

        return goods;
    }

    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andLike("id","%"+searchMap.get("id")+"%");
            }
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andLike("sn","%"+searchMap.get("sn")+"%");
            }
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
            }
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
            }
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
            }
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
            }
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                criteria.andLike("saleService","%"+searchMap.get("saleService")+"%");
            }
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
            }
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                criteria.andLike("specItems","%"+searchMap.get("specItems")+"%");
            }
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                criteria.andLike("paraItems","%"+searchMap.get("paraItems")+"%");
            }
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                criteria.andLike("isMarketable","%"+searchMap.get("isMarketable")+"%");
            }
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                criteria.andLike("isEnableSpec","%"+searchMap.get("isEnableSpec")+"%");
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andLike("status","%"+searchMap.get("status")+"%");
            }

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
